﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace AsyncServer_1
{
    public class Conn
    {
        public const int BufferSize = 1024;
        public Socket socket;
        public bool bInUse = false;
        public byte[] readBuffer;
        public int bufferCount = 0;

        public Conn()
        {
            readBuffer = new byte[BufferSize];
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="pSocket"></param>
        public void Init(Socket pSocket)
        {
            socket = pSocket;
            bInUse = true;
            bufferCount = 0;
        }

        /// <summary>
        /// 缓冲区剩余的字节数
        /// </summary>
        /// <returns></returns>
        public int BuffRemain()
        {
            return BufferSize - bufferCount;
        }

        /// <summary>
        /// 获取客户端地址
        /// </summary>
        /// <returns></returns>
        public string GetAddress()
        {
            if (bInUse)
            {
                return socket.RemoteEndPoint.ToString();
            }
            return " 无法获取地址";
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            if (!bInUse)
            {
                return;
            }

            Console.WriteLine($"[断开连接] {GetAddress()}");
            socket.Close();
            bInUse = false;
        }
    }
}
